package com.zgl.modules.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zgl.modules.user.DTO.UserDTO;
import com.zgl.modules.user.entity.CodeEntity;
import com.zgl.modules.user.entity.User;
import com.zgl.modules.user.mapper.UserMapper;
import com.zgl.modules.user.service.UserService;
import com.zgl.modules.wallet.entity.WalletEntity;
import com.zgl.modules.wallet.service.impl.WalletServiceImpl;
import com.zgl.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

@Service
public class UserServiceImpl  implements UserService {
    @Autowired
    private CodeServiceImpl codeService;
    @Resource
    private UserMapper userMapper;
    @Autowired
    private WalletServiceImpl walletService;
    @Override
    public R saveOne(  User user) {
        if(userMapper.insert(user)==1){
            return R.success();
        }else {
            return  R.error();
        }

    }

    @Override
    public R removeOne(Integer id) {
        if(userMapper.deleteById(id)==1){
            return R.success();
        }else {
            return  R.error();
        }
    }

    @Override
    public R modifyOne(User user) {
        if(userMapper.updateById(user)==1){
            return R.success();
        }else {
            return  R.error();
        }
    }

    @Override
    public R getOne(Integer id) {
       User user=userMapper.selectById(id);
       return R.success(user);
    }
    @Override
    public R getOneByName(String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>() ;
        queryWrapper.eq("username",name);
        User user=userMapper.selectOne(queryWrapper);
        return R.success(user);
    }
    //用户注册
    @Transactional
    public R register(@RequestBody UserDTO user){
        CodeEntity codeEntity=(CodeEntity)codeService.getOne(user.getEmail()).getData();

        if(codeEntity==null){return R.error("邮箱不一致");}
        int mycode=codeEntity.getValue();
        String code= Integer.toString(mycode);
        //校验验证码是否正确
        if(code.equals(user.getCode())){
            int uuid= (int) ((Math.random() * 9 + 1) * 100000);
            Integer uuidit = Integer.valueOf(uuid);
            User userEntity=new User(uuidit,user.getUsername(),user.getPassword(),user.getEmail(),null,0);
            codeEntity.setUsed(1);
            codeService.modifyOne(codeEntity);
            userMapper.insert(userEntity);
            walletService.savaOne(new WalletEntity(null,"0", uuidit.toString()));
            return R.success();
        }
        return R.error("验证码错误，请重试");


    }
}
